package thin4ca

import scala.collection.mutable.Map

class Entity(val typez: String) {

  var id: String = "";
  val attrs: Map[String, Any] = Map()
  
  def this(typez: String, newAttrs: Map[String, Any]) = {
    this(typez)
    this.attrs ++ newAttrs.toList
  }
  
  def set(name: String, value: Any) {
    setInverse(name, value)
    value match {
      case e: Entity => e.setInverse(name, this)
      case _ => ()
    }
  }

  def setInverse(name: String, value: Any) {
    attrs += (name -> value)
  }

  def get(name: String) : Any = {
    
    println("get:name " + name)
    var attrName = name
    if (name contains ".") {
      attrName = name.takeWhile( !_.equals('.') ).mkString
    }
    println("attrName " + attrName)
    attrs get attrName match {
      case Some(value) =>  value match {
        case e: Entity =>  {
          println("get:some entity " + e)
          val remaining = name.drop(attrName.length+1).mkString
          if (remaining isEmpty)
            e
          else
            e get remaining
        }
	    case _ => println("get:primitive attr " + value); value
      }
      case None =>  error("Attribute " + name + " not found on " + this)
    }
  }
  
  def readAttrs: scala.collection.immutable.Map[String, Any] = scala.collection.immutable.Map.empty ++ attrs
  
  override def toString =
    "Entity[" + typez + ", attrs: " + attrs.keys.toList + "]";
}
